package com.pai.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.pai.entity.PaiTask;
import com.pai.entity.User;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
 * xml文件操作工具类。
 * @author Jeff
 *
 */
public class XMLUtil {
	public static final XStream xstream = new XStream(new DomDriver());
	
	//设置别称
	private static void setAlias(){
		xstream.alias("paitask", PaiTask.class);
		xstream.alias("user", User.class);
	}
	
	/**
	 * 读取xml文件，并转化成List对象。
	 * @param filepath 文件路径
	 * @return
	 */
	public static List<PaiTask> getListFromXml(String filepath){
		setAlias();
		return (List<PaiTask>) xstream.fromXML(new File(filepath));
	}
	
	/**
	 * 讲List对象保存成xml文件。
	 * @param filepath
	 * @param list
	 */
	public static void saveListToXml(String filepath,List list){
		setAlias();
		try {
			PrintWriter pw = new PrintWriter(filepath,"UTF-8");
			xstream.toXML(list, pw);
		} catch (FileNotFoundException e) {
			System.out.println(filepath + "文件未找到。");
		} catch (UnsupportedEncodingException e) {
			System.out.println("编码不支持");
		}
		
	}
	
	
	//测试方法。
	public static void main(String[] args){
		setAlias();
		List<PaiTask> hehe = new ArrayList<PaiTask>();
		hehe.add(createTask());
		/*		hehe.add(createTask());
		hehe.add(createTask());
		hehe.add(createTask());*/
		saveListToXml("res/history/downloadTask.xml", hehe);
		List<PaiTask> xixi = getListFromXml("res/history/downloadTask.xml");
		System.out.println(""+xixi.size());
		
	}
	//测试方法
	public static PaiTask createTask(){
		PaiTask pai = new PaiTask();
		pai.setFileName("aaaa");
		pai.setFileSize(1321321312L);
		pai.setFileSrc("dsadfadsf");
		pai.setBeginTime(new Date());
		User user = new User();
		user.setUserHeadNum(1);
		user.setUsername("bbb");
		pai.setFromUser(user);
		return pai;
	}
}
